﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Objects;
namespace AbingtonBooks.Pages.Books
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["search"] != null)
            {
                string search = Session["search"].ToString();
                searchBox.Text = search;
                getResults(search);
                Session.Remove("search");
            }

        }

        protected void searchButton_Click(object sender, EventArgs e)
        {
            string search = searchBox.Text;
            getResults(search);


        }
        private void getResults(string search) {

            using (dbAbingtonBooks context = new dbAbingtonBooks())
            {
                var results = context.getSearchResults(search);
                if (results != null) {
                    BookGrid.DataSource = results;
                    BookGrid.DataBind();
                }
            }
        }

        protected void btnAdd_Command(object sender, CommandEventArgs e)
        {
            if (Session["Customer"] != null)
            {
                int bookId = Convert.ToInt32(e.CommandArgument);
                ShoppingCart cart = ShoppingCart.getShoppingCart();
                using (dbAbingtonBooks context = new dbAbingtonBooks())
                {
                    Book book = context.Books.Where(b => b.BookId == bookId).FirstOrDefault();
                    cart.addToCart(book);
                    Response.Redirect("~/Pages/Cart");

                }
            }
            else {
                Session["ToGo"] = "~/Pages/Books/ViewBook/Default.aspx?id=" + e.CommandArgument.ToString();
                Response.Redirect("~/Pages/Login");
            }
        }

    }
}